package injection;

import domain.SuperUser;
import domain.User;
import org.junit.Test;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;

/**
 * 延迟注入，可以用于注册一些非必要性的依赖
 * @author jackcfan
 * @date 2021/9/18
 */
@Configuration
public class LazyAnnotationInjection {
    @Autowired
    User user;

    // ObjectProvider 延迟注入，通过 getObject 获取依赖
    @Autowired
    ObjectProvider<SuperUser> superUserProvider;

    @Test
    public void test(){
        // 注解 + xml 配置文件
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 1.注册注解 Bean
        applicationContext.register(this.getClass());

        // 2.读取 xml 配置文件
        // AnnotationConfigApplicationContext 实现了注册中心接口
        // XmlBeanDefinitionReader(BeanDefinitionRegistry registry)
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);

        // 加载 xml 资源，解析并生成 BeanDefinition
        beanDefinitionReader.loadBeanDefinitions("dependency-setter-injection.xml");

        applicationContext.refresh();

        LazyAnnotationInjection lazy = applicationContext.getBean(LazyAnnotationInjection.class);

        System.out.println("user:"+lazy.user);
        System.out.println("superUser:"+lazy.superUserProvider.getObject());

        applicationContext.close();
    }
}
